package com.alpha.module.sys.service.impl;

import com.alpha.module.sys.entity.SysMenu;
import com.alpha.module.sys.model.SysMenuDTO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.alpha.common.utils.PageUtils;
import com.alpha.common.utils.BusinessException;

import com.alpha.module.sys.dao.SysMenuMapper;
import com.alpha.module.sys.service.SysMenuService;


@Service("sysMenuService")
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public PageUtils queryPage(SysMenuDTO vo) {
        PageHelper.startPage(vo.getPageNo(), vo.getPageSize());
        List<SysMenuDTO> vos = new ArrayList<>();
        List<SysMenu> list = this.sysMenuMapper.queryList(vo);
        for (SysMenu menu : list) {
            SysMenuDTO menuVO = SysMenuDTO.instance(menu);
            vos.add(menuVO);
        }
        List<SysMenuDTO> sList = treeList(vos,0L);
        return new PageUtils(new PageInfo<>(sList));
    }

    private List<SysMenuDTO> treeList(List<SysMenuDTO> list, long parentId) {
        List<SysMenuDTO> childList = this.getChildList(list, parentId);
        if (childList.size() > 0) {
            for (SysMenuDTO sysMenuDTO : childList) {
                sysMenuDTO.setChildren(treeList(list, sysMenuDTO.getId()));
            }
            return childList;
        } else {
            return null;
        }
    }

    private List<SysMenuDTO> getChildList(List<SysMenuDTO> list, long parentId) {
        List<SysMenuDTO> childList = new ArrayList<>();
        for (SysMenuDTO menuVO : list) {
            if (menuVO.getParentId() == parentId) {
                childList.add(menuVO);
            }
        }
        return childList;
    }

    @Override
    public void save(SysMenu sysMenu) {
        sysMenu.setCreateTime(new Date());
            sysMenuMapper.insertSelective(sysMenu);
    }

    @Override
    public SysMenu getById(Long id) {
        if (id <= 0) {
            throw new BusinessException("参数错误");
        }
        return sysMenuMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateById(SysMenu sysMenu) {
        sysMenu.setModifyTime(new Date());
            sysMenuMapper.updateByPrimaryKeySelective(sysMenu);
    }


}